const fs = require("fs");
const archiver = require("archiver");
const path = require("path");
const prompts = require("prompts");

//忽略文件
const ignoreFile = "config.js";
// 定义打包列表
const targetList = [
  {
    name: "basic-web",
    sourceDir: "E:/chen/mes-basic-web/dist",
    targetName: "basic-web.rar",
  },
  {
    name: "mes-web",
    sourceDir: "E:/chen/mes-web/dist",
    targetName: "mes-web.rar",
  },
  {
    name: "mes-op-web",
    sourceDir: "E:/chen/mes-op-web/dist",
    targetName: "mes-op-web.rar",
  },
];

// 询问用户选择需要打包的应用
(async () => {
  const response = await prompts({
    type: "select",
    name: "selectedApp",
    message: "请选择需要压缩的应用：",
    choices: targetList.map((app) => ({ title: app.name, value: app.name })),
  });

  const selectedApp = targetList.find(
    (app) => app.name === response.selectedApp
  );

  if (selectedApp) {
    createArchive(selectedApp);
  } else {
    console.log("选择的应用不存在.");
  }
})();

// 创建压缩包函数
function createArchive(app) {
  const outputFileName = path.join(
    require("os").homedir(),
    "Desktop",
    app.targetName
  );

  const output = fs.createWriteStream(outputFileName);
  const archive = archiver("zip", { zlib: { level: 9 } });

  output.on("close", function () {
    console.log(archive.pointer() + " total bytes");
    console.log("压缩包创建成功.");
  });

  archive.on("error", function (err) {
    throw err;
  });

  archive.pipe(output);

  // 递归函数，用于深度遍历文件夹
  function addFolderToArchive(folderPath) {
    const files = fs.readdirSync(folderPath);
    files.forEach((file) => {
      if (file === ignoreFile) {
        return;
      }
      const filePath = path.join(folderPath, file);
      if (fs.statSync(filePath).isDirectory()) {
        archive.directory(filePath, file);
      } else {
        archive.file(filePath, { name: file });
      }
    });
  }

  fs.readdir(app.sourceDir, (err, files) => {
    if (err) {
      console.error("读取目录失败:", err);
      return;
    }

    addFolderToArchive(app.sourceDir);

    archive.finalize();
  });
}
